<?php 
namespace lib;
class AesRsa_Encrypter{
    public static function encode($data , $key , $publicKey){//加密
        $aesKey = self::randomizeCase(self::randomCaseMd5());
        $encodedData = base64_encode($data);
        $encryptedData = self::aesEncrypt($encodedData, $aesKey);
        $rsaEncryptedAesKey = self::rsaEncrypt($aesKey.$encryptedData, $publicKey);
        $encryptedAesKey = self::aesEncrypt($rsaEncryptedAesKey, $key);
        return base64_encode($encryptedAesKey);
    }
    public static function decode($data , $key , $privateKey){//解密
        
        $data  = base64_decode($data);
        $rsaEncryptedAesKey = self::aesDecrypt($data,$key);
        if ($rsaEncryptedAesKey === false) {
            return false;
        }
        $aestoken = self::rsaDecrypt($rsaEncryptedAesKey, $privateKey);
        if ($aestoken === false) {
            return false;
        }
        $aeskey   = substr($aestoken, 0, 32);
        $aesdata  = substr($aestoken,32);
        $decodedData = self::aesDecrypt($aesdata, $aeskey);
        if ($decodedData === false) {
            return false;
        }
        return base64_decode($decodedData);
    }
    
    private static function rsaEncrypt($data, $publicKey){//rsa 公钥加密
        openssl_public_encrypt($data, $encrypted, $publicKey);
        return base64_encode($encrypted);
    }
    private static function rsaDecrypt($data, $privateKey){//rsa 私钥解密
        openssl_private_decrypt(base64_decode($data), $decrypted, $privateKey);
        return $decrypted;
    }
    private static function aesEncrypt($data, $key) {//ase 加密
        $iv = random_bytes(16);
        $encrypted = openssl_encrypt($data, 'AES-256-CBC', $key, OPENSSL_RAW_DATA, $iv);
        return base64_encode($iv . $encrypted);
    }
    private static function aesDecrypt($data, $key) { //ase 解密
        $data = base64_decode($data);
        $iv = substr($data, 0, 16);
        $encrypted = substr($data, 16);
        // 解密
        $decrypted = openssl_decrypt($encrypted, 'aes-256-cbc', $key, OPENSSL_RAW_DATA, $iv);
        return $decrypted;
    }
    private static function randomCaseMd5($length = 32) {
        $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $charactersLength = strlen($characters);
        $randomString = '';
        for ($i = 0; $i < $length; $i++) {
            $randomString .= $characters[rand(0, $charactersLength - 1)];
        }
        return md5($randomString);
    }
    
    private static function randomizeCase($string) {
        $result = '';
        for ($i = 0; $i < strlen($string); $i++) {
            $char = $string[$i];
            if (ctype_alpha($char)) {
                $result .= (rand(0, 1) === 0) ? strtoupper($char) : strtolower($char);
            } else {
                $result .= $char;
            }
        }
        return $result;
    }
}


?>